// Description: 描述
package interceptor

import (
	"context"
	"fmt"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"gitlab.vspncd.com/mic/common/xerror"
)

// rpc 日志中间件, 把日志进行打印
func LoggerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
	resp, err = handler(ctx, req)
	if err != nil {
		causeErr := errors.Cause(err)
		if e, ok := causeErr.(xerror.Error); ok {
			e.Log(ctx, fmt.Sprintf("rpc err %s ", info.FullMethod))
			// 转成 grpc err
			code := uint32(e.Code())
			if code == 0 {
				code = uint32(codes.Aborted)
			}
			err = status.Error(codes.Code(code), e.Message())
		} else {
			logx.WithContext(ctx).Errorf("rpc err %s %+v", info.FullMethod, err)
		}
	}
	return resp, err
}
